<?php 

/**
* 数据库类
*/
class Model
{
	//公用对象$db   static静态属性 减少多次链接，节省资源
	public static $db;
	public $table;
	public $error;
	public $errno;
	public $where;
	//构造函数参数可以接到M方法new Model返回的表名
	function __construct($table=null)
	{	
		//如果有传$table进入这里
		if ($table) {
			//把接进来的$table放到属性里
			$this->table=$table;
		}
		if(!self::$db){
			var_dump($table);
			try{ 
			//把$db对象转为这个类的属性:$this->db,以便其他方法也可以用到db
				self::$db = new PDO("mysql:host=".C('db_host').";dbname=".C('db_dbname').";charset=utf8",C('db_user'),C('db_password'));

			/*var_dump($db->errorCode());*/
			}catch(PDOException  $e ){

				echo "Error: ".$e;exit;

			}
		}

	}


	public function add ($data)
	{
		//var_dump($data);  //要插入的数据是个数组
		//var_dump($this->table);  //被插入数据的表名

		//implode把data数组拼接成字符串
		$values = implode("','", $data);
		$keys = implode(',', array_keys($data));
		//var_dump($values);
		//var_dump($keys);

		$sql = "insert into ".$this->table." (".$keys.") values('".$values."')";

		//var_dump($sql);
		
		return $this->exec($sql); //return给index的add
		
	}

	public function exec($sql)
	{
		$res = self::$db->exec($sql);
		//var_dump($res);
		if (!$res) {
			$this->error=$this->db->errorInfo()[2];
			$this->errno=$this->db->errorCode();
		}
		return $res; //return给上面的$this->exec($sql)
	}

	public function query($sql)
	{
		$res = self::$db->query($sql);
		
		if (!$res) {
			$this->error=$this->db->errorInfo()[2];
			$this->errno=$this->db->errorCode();
			return false;
		}
		return $res->fetchAll(PDO::FETCH_ASSOC); 
	}


	public function getError()
	{
		return"错误代码:".$this->errno."错误信息:".$this->error;
	}


	public function where($where)
	{
		$this->where =" where ".$where;

		//连贯操作 返回当前对象，
		return $this;
	}


	//find是找数据
	public function find()
	{
		$sql = "select * from ".$this->table.$this->where;

		//var_dump($sql);exit;

		return $this->query($sql);
	}


	public function save($data)
	{	
		//var_dump($data);

		$str = '';

		foreach ($data as $k => $v) {
			$str .=$k."='".$v."',";
		}

		$str = rtrim($str,',');

		//var_dump($str);

		$sql="update ".$this->table." set ".$str.$this->where;

		return $this->exec($sql); 
	}




	public function delete($id=null)
	{	
		$key = $this->getPri();
		//var_dump($key);

		if ($id) {
			$sql = "delete from ".$this->table." where ".$key."=".$id;
			//var_dump($sql);
		}else{
			$sql = "delete from ".$this->table.$this->where;
		}
		//var_dump($sql);exit;
		
		return $this->exec($sql);
	}


	//获取表主键
	public function getPri()
	{	
		$sql = "desc ".$this->table;

		$res = $this->query($sql);

		//var_dump($res);
		foreach ($res as $v) {
			if ($v['Key']=='PRI') {
				return $v['Field'];
			}
		}
	}















}

































 ?>